<?php
namespace app\controller;


use app\model\Article;
use app\model\Banner;
use app\model\Column;
use app\model\Company;
use app\model\Language;
use app\model\Site;
use app\validate\User;
use think\Controller;
use think\Db;
use app\model\User as UserModel;
class Admin extends Controller
{
    protected $middleware = [
        'CheckLogin' => ['except' => ['login','check'] ],
//        'Hello' => ['only' => ['hello'] ],
        ];
    protected $site_id;
    protected $site_name;
    protected $beforeActionList = [
        'setSite'=> ['except'=>'login,check,logout'],
    ];
    public function setSite()
    {
        $info = session('info');
//        echo '<pre>';
        $this->site_id = $info['site']['id'];
        $this->site_name = $info['site']['site_name'];
    }
    public function index()
    {
        $this->assign([
            'company'=>Company::CompanyList(),
            'language'=>Language::languageList()
        ]);
        return $this->fetch();
    }
    public function welcome()
    {
        return $this->fetch();
    }
    public function login()
    {

        return $this->fetch();
    }
    public function logout()
    {
        session('info',null);
        return json(['code'=>200,'msg'=>'退出成功']);
    }
    public function check()
    {
        $data = input();
        $validate = new User();
        if(!$validate->check($data)){
            return json(['code'=>203,'msg'=>$validate->getError()]);
        }
        $res = \app\model\User::checkUser($data);
        return $res;
    }
    public function changeSite()
    {
        $data = input();
        $info = session('info');
        $condition = $data['type'] == 'company' ? ['company_id'=>$data['id'],'language_id'=>$info['language']['id']] : ['company_id'=>$info['company']['id'],'language_id'=>$data['id']];
        $res = Db::name('site')->where($condition)->field('id,site_name,site_url')->find();
        if($res){
            //修改session里的site/company/language
            $info['site'] = $res;
            if($data['type'] == 'company'){
                $info['company'] = Db::name('company')->where('id',$data['id'])->field('id',$data['id'])->find();
            }else{
                $info['language'] = Db::name('language')->where('id',$data['id'])->field('id,title,en_title,zh_short_title,en_short_title')->find();
            }
            session('info',$info);
            $rel = ['code'=>200,'msg'=>'切换成功,请按F5刷新页面','data'=>$res];
        }else{
            $rel = ['code'=>202,'msg'=>'切换失败,是否新建站点'];
        }
        return $rel;
    }
    public function column()
    {
        if($this->request->isAjax()){
            $res = Db::name('column')
                ->where('site_id',$this->site_id)
                ->field('id,site_id,pid,title,english,sort,keyword,description,seo_title,seo_keyword,seo_description,url,img,bckimg,indexImg,drop,show,additional1,additional2,create_time')
                ->order('sort','desc')
                ->select();
            return json(['code'=>200,'msg'=>'','count'=>count($res),'data'=>$res]);
        }
        return $this->fetch();
    }
    public function editColumn($id=null,$pid=null)
    {
        $session = session('info');
        if($this->request->isAjax()){
            if($this->request->isGet()){
                $info = Column::findColumn((input('id')));
                return $info;
            }else{
                $data = input();
                $column = new Column();
                if(isset($data['content']) && $data['content']){
                    $data['content'] = htmlspecialchars_decode($data['content']);
                }
                if(isset($data['id']) && $data['id']){
                    $res = $column->save($data,['id',$data['id']]);
                }else{
                    unset($data['id']);
                    $res = $column->save($data);
                }
                return json(['code'=>$res ? '200' : '202','msg' => $res ? '保存成功' : '保存失败']);
            }
        }
        return $this->fetch();
    }
    public function delColumn()
    {
        $a = $this->findSubColumn([input('id')],[]);
        $res = Column::destroy($a);
        return $res;
    }
    public function findSubColumn($init,$total=[]){
        $curr = Db::name('column')->where('pid','in',$init)->column('id');
        $total = array_merge($init,$total);
        if(empty($curr)){
            return array_unique($total);
        }else {
            return $this->findSubColumn($curr,$total);
        }
    }
    public function article($column_id)
    {
        if($this->request->isAjax()){
            if($this->request->isGet()){
                $data = input();
                $condition[] = ['column_id','=',$data['column_id']];
                if(isset($data['search']) && $data['search']){
                    $condition[] = ['title|short_title|keyword|description|seo_title|seo_keyword|seo_description','like','%'.$data['search'].'%'];
                }
                if(isset($data['date']) && !empty($data['date'])){
                    foreach($data['date'] as $key => $val){
                        $data['date'][$key] = strtotime(trim($data['date'][$key]));
                    }
                    $condition[] = ['create_time','between',$data['date'][0] . ',' . $data['date'][1]];
                }
                $list = Article::field('id,site_id,column_id,title,short_title,keyword,description,seo_title,seo_keyword,seo_description,thumbnail,date,views,sort,content,create_time,update_time,delete_time,lb,zhiding')->where($condition)->order('id','desc')->paginate($data['limit']);
                return json(['code'=>0,'msg'=>'','count'=>Article::where($condition)->count(1),'data'=>$list->all()]);
            }
        }
        return $this->fetch();
    }
    public function delArticle()
    {
        $data = input('id');
        $res = Article::destroy($data);
        return json(['code'=>$res ? 200 : 202,'msg' => $res ? '删除成功' : '删除失败']);
    }
    public function editArticle($id=null,$column_id=null)
    {
        if($this->request->isAjax()){
            if($this->request->isGet()){
                $id = input('id');
                $res = Article::alias('a')->leftJoin('file b','a.file = b.src')->field("a.id,a.site_id,a.column_id,a.title,a.short_title,a.keyword,a.description,a.seo_title,a.seo_keyword,a.seo_description,a.thumbnail,a.date,a.views,a.sort,a.content,a.create_time,a.update_time,a.delete_time,a.lb,a.zhiding,(case b.name when not null then b.name else '' end) as file_name")->get($id);
                return ['code'=>!$res ? 202:200,'data'=>!$res ? [] : $res];
            }
            if($this->request->isPost()){
                $data = input();
                $article = new Article();
                if(isset($data['id']) && $data['id']){
                    $id = $data['id'];
                    unset($data['id']);
                    $res = $article->save($data,['id'=>$id]);
                }else{
                    $res = $article->save($data);
                    $id = $article->id;
                }
                return json(['code'=>$res ? 200 : 202,'msg'=>$res ? '保存成功' : '保存失败','id' =>$id]);
            }
        }
        return $this->fetch();
    }
    public function siteList()
    {
        if($this->request->isAjax()){
            $data = input();
            $res = Db::name('site')
                ->alias('a')
                ->leftJoin('company b','a.company_id = b.id')
                ->leftJoin('language c','a.language_id = c.id')
                ->field('a.id,a.site_name,a.site_url,b.company_name as company_name,a.keyword,a.address,a.phone,a.email,a.fax,a.hlogo,a.flogo,a.public_img,a.record,a.browsing,c.title as language')
                ->select();
            $res = ['code'=>0,'msg'=>'','count'=>count($res),'data'=>$res];
            return json($res);
        }
        return $this->fetch();
    }
    public function editSite($id=null)
    {
        if($this->request->isAjax()){
            if($this->request->isPost()){
                $data = input();
                $res = Site::saveSite($data);
                return $res;
            }else if($this->request->isGet()){
                $id = input('id');
                $info = Site::info($id);
                return $info;
            }

        }
        return $this->fetch();
    }
    public function delSite()
    {
        $data = input('ids');
        return Site::delSite($data);
    }
    public function getCompanyLanguage()
    {
        return json(['company'=>Company::CompanyList(),'language'=>Language::languageList()]);
    }
    public function company()
    {
        if($this->request->isAjax()){
            $res = Company::CompanyList();
            return json(['code'=>0,'msg'=>'','data'=>$res]);
        }
        return $this->fetch();
    }
    public function editCompany()
    {
        $data = input();
        if(isset($data['id']) && $data['id']){

            $res = Db::name('company')->where('id',$data['id'])->update(['company_name'=>$data['company_name']]);
        }else{
            $res = Db::name('company')->insert($data);
        }
        return $res;
    }
    public function delCompany()
    {
        $id = input('id');
        $res = Db::name('company')->where('id',$id)->delete();
        return $res;
    }
    public function language()
    {
        if($this->request->isAjax()){
            return json(['code'=>0,'msg'=>'','data'=>Language::languageList()]);
        }
        return $this->fetch();
    }
    public function editLanguage()
    {
        $data = input();
        if(isset($data['id']) && $data['id']){
            return Db::name('language')->update($data);
        }else{
            return Db::name('language')->insert($data);
        }
    }
    public function delLanguage()
    {
        return Db::name('language')->where('id',input('id'))->delete();
    }
    public function articleWithoutColumn()
    {
        if($this->request->isAjax()){
            if($this->request->isGet()){
                $article = new Article();
                $data = input();
                $condition = [];
                if(isset($data['search']) && $data['search']){
                    $condition[] = ['a.title|a.short_title|a.keyword|a.description|a.seo_title|a.seo_keyword|a.seo_description','like','%'.$data['search'].'%'];
                }
                if(isset($data['date']) && !empty($data['date'])){
                    foreach($data['date'] as $key => $val){
                        $data['date'][$key] = strtotime(trim($data['date'][$key]));
                    }
                    $condition[] = ['a.create_time','between',$data['date'][0] . ',' . $data['date'][1]];
                }
                if(isset($data['column_id']) && $data['column_id']){
                    $condition[] = ['a.column_id','in',$data['column_id']];
                }
                $list = $article->alias('a')
                    ->leftJoin('file b','a.file = b.src')
                    ->leftJoin('column c','a.column_id = c.id')
                    ->where($condition)
                    ->field("a.id,a.site_id,a.column_id,a.title,a.short_title,a.keyword,a.description,a.seo_title,a.seo_keyword,a.seo_description,a.thumbnail,a.date,a.views,a.sort,a.create_time,a.zhiding,(case b.name when not null then b.name else '无' end) as file_name,c.title as column_name")
                    ->order('id','desc')
                    ->paginate($data['limit']);
                $res = ['code'=>0,'msg'=>'','data'=>$list->all(),'count'=>$list->total()];
                return json($res);
            }
        }
        return $this->fetch();
    }
    public function columnTree()
    {
        $column = new Column();
        $list = $column::field("title,id,pid,'title' as field")->select()->toArray();
        $list_tree = buildTree(0,$list);
        return $list_tree;
    }
    public function articleDeleted()
    {
        if($this->request->isAjax()){
            if($this->request->isGet()){
                $article = new Article();
                $data = input();
                $condition = [];
                if(isset($data['search']) && $data['search']){
                    $condition[] = ['a.title|a.short_title|a.keyword|a.description|a.seo_title|a.seo_keyword|a.seo_description','like','%'.$data['search'].'%'];
                }
                if(isset($data['date']) && !empty($data['date'])){
                    foreach($data['date'] as $key => $val){
                        $data['date'][$key] = strtotime(trim($data['date'][$key]));
                    }
                    $condition[] = ['a.create_time','between',$data['date'][0] . ',' . $data['date'][1]];
                }
                if(isset($data['column_id']) && $data['column_id']){
                    $condition[] = ['a.column_id','in',$data['column_id']];
                }
                $list = Article::onlyTrashed()
                    ->alias('a')
                    ->leftJoin('file b','a.file = b.src')
                    ->leftJoin('column c','a.column_id = c.id')
                    ->where($condition)
                    ->field("a.id,a.site_id,a.column_id,a.title,a.short_title,a.keyword,a.description,a.seo_title,a.seo_keyword,a.seo_description,a.thumbnail,a.date,a.views,a.sort,a.create_time,delete_time,(case b.name when not null then b.name else '无' end) as file_name,c.title as column_name")
                    ->order('id','desc')
                    ->paginate($data['limit']);
//                echo Db::getLastSql();
                $res = ['code'=>0,'msg'=>'','data'=>$list->all(),'count'=>$list->total()];
                return json($res);
            }
        }
        return $this->fetch();
    }
    public function trueDelArticle()
    {
        $id = input('id');
        try{
            foreach($id as $val){
                $res = Article::onlyTrashed()->find($val);
                $res->delete(true);
            }
            $res = ['code'=>200,'msg'=>'删除成功'];
        }catch (\Exception $e){
            $res = ['code'=>202,'msg'=>'删除失败,原因:'.$e->getMessage()];
        }
        return $res;
    }
    public function restoreArticle()
    {
        $id = input('id');
        try{
            foreach($id as $val){
                $res = Article::onlyTrashed()->find($val);
                $res->restore();
            }
            $res = ['code'=>200,'msg'=>'恢复成功'];
        }catch (\Exception $e){
            $res = ['code'=>202,'msg'=>'恢复失败,原因:'.$e->getMessage()];
        }
        return $res;
    }
    public function banner()
    {
        if($this->request->isAjax()){
            $banner = new Banner();
            $data = input();
            $list = $banner->field('id,title,url,img,create_time')->paginate($data['limit']);
            return $list;
        }
        return $this->fetch();
    }
    public function editBanner($id=null){
        if($this->request->isAjax()){
            $data = input();
            $banner = new Banner();
            if($this->request->isPost()){
                if(isset($data['id']) && $data['id']){
                    $res = $banner->save($data,['id'=>$data['id']]);
                }else{
                    $data['site_id'] = session('info')['site']['id'];
                    $res = $banner->save($data);
                }
                return $res;
            }else{
                $res = $banner->find($data['id']);
                return $res;
            }
        }
        return $this->fetch();
    }
    public function delBanner()
    {
        $data = input();
        $banner = new Banner();
        $res = Banner::destroy($data);
        return $res;
    }
    public function userSetting()
    {
        if($this->request->isAjax()){
            if($this->request->isGet()){
                $session = session('info');
                return json($session['info']);
            }
            if($this->request->isPost()){
                $data = input();
                $session = session('info');
                try{
                    $res = Db::name('user')->where('user_name',$session['info']['user_name'])->update($data);
                    $session['info'] = $data;
                    session('info',$session);
                    return json(['code'=>200,'msg'=>'修改成功']);
                }catch(\Exception $e){
                    return json(['code'=>202,'msg'=>'修改失败,原因:'.$e->getMessage()]);
                }
            }
        }
        return $this->fetch();
    }
    public function userPassword()
    {
        if($this->request->isPost()){
            $data = input();
            $user_pass = UserModel::where('id',session('info')['info']['id'])->value('password');
            if(md5($data['old_password']) != $user_pass){
                $res = ['code'=>202,'msg'=>'原始密码输入错误'];
                return json($res);
            }
            try{
                $user = new UserModel();
                $user->save(['password'=>md5($data['new_password'])],['id'=>session('info')['info']['id']]);
                $res = ['code'=>200,'msg'=>'修改成功'];
            }catch (\Exception $e){
                $res = ['code'=>202,'msg'=>'修改失败,原因:'.$e->getMessage()];
            }
            return json($res);
        }
        return $this->fetch();
    }























}